package com.lzb.watermarkcamera.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzb.watermarkcamera.AppConfig;
import com.lzb.watermarkcamera.BaseAc;
import com.lzb.watermarkcamera.Content;
import com.lzb.watermarkcamera.R;
import com.lzb.watermarkcamera.basic.utils.FileUtil;
import com.lzb.watermarkcamera.basic.utils.SPUtil;
import com.lzb.watermarkcamera.bean.Hours24Bean;
import com.lzb.watermarkcamera.bean.PersonalCardBean;
import com.lzb.watermarkcamera.bean.WatermarkBean;
import com.lzb.watermarkcamera.databinding.ActivityEditCustomWatermarkBinding;
import com.lzb.watermarkcamera.dialog.CustomTextDialog;
import com.lzb.watermarkcamera.dialog.NumberDialog;
import com.lzb.watermarkcamera.dialog.PermissionExplainDialog;
import com.lzb.watermarkcamera.dialog.SelTimeDialog;
import com.lzb.watermarkcamera.utils.AppSpUtils;
import com.lzb.watermarkcamera.utils.CityUtils;
import com.lzb.watermarkcamera.utils.MyMediaRecorder;
import com.lzb.watermarkcamera.utils.OkhttpUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.text.DecimalFormat;

public class EditCustomWatermarkActivity extends BaseAc<ActivityEditCustomWatermarkBinding> implements View.OnClickListener, SensorEventListener {

    public static WatermarkBean watermarkBean;
    private WatermarkBean.CustomBean customBean;
    private boolean isHaveLocationPermission, isHaveRecordAudioPermission;
    private SensorManager sensorManager;
    private long lastUpdateTime = 0;
    private boolean hasRecord = false;
    private MyMediaRecorder mRecorder;
    private Handler mHandler;
    float volume = 10000;

    private final Runnable mTaskUpdateTime = new Runnable() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void run() {
            if (!hasRecord) return;
            volume = mRecorder.getMaxAmplitude();  //获取声压值
            if (volume > 0 && volume < 1000000) {
                float value = 20 * (float) (Math.log10(volume));
                int val = (int) value;
                if (val < 30) {
                    mDataBinding.tvDecibel.setText(val + getString(R.string.decibel_text1));
                    mDataBinding.customWatermark.tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text1));
                } else if (val < 60) {
                    mDataBinding.tvDecibel.setText(val + getString(R.string.decibel_text2));
                    mDataBinding.customWatermark.tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text2));
                } else if (val < 90) {
                    mDataBinding.tvDecibel.setText(val + getString(R.string.decibel_text3));
                    mDataBinding.customWatermark.tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text3));
                } else {
                    mDataBinding.tvDecibel.setText(val + getString(R.string.decibel_text4));
                    mDataBinding.customWatermark.tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text4));
                }
            }
            mHandler.postDelayed(this, 1000);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_edit_custom_watermark;
    }

    @Override
    protected void initView() {
        mDataBinding.ivEditCustomWatermarkBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.tvAddCustomWatermark.setOnClickListener(this);
        mDataBinding.ivOpenWatermarkVerification.setOnClickListener(this);
        mDataBinding.ivOpenLogo.setOnClickListener(this);
        mDataBinding.llLogo.setOnClickListener(this);
        mDataBinding.ivOpenPersonalCard.setOnClickListener(this);
        mDataBinding.llPersonalCard.setOnClickListener(this);
        mDataBinding.ivOpenCustomText.setOnClickListener(this);
        mDataBinding.llCustomText.setOnClickListener(this);
        mDataBinding.ivOpenNumber.setOnClickListener(this);
        mDataBinding.llNumber.setOnClickListener(this);
        mDataBinding.ivOpenCount.setOnClickListener(this);
        mDataBinding.llCount.setOnClickListener(this);
        mDataBinding.ivOpenTime.setOnClickListener(this);
        mDataBinding.llTime.setOnClickListener(this);
        mDataBinding.ivOpenWeather.setOnClickListener(this);
        mDataBinding.llWeather.setOnClickListener(this);
        mDataBinding.ivOpenLocation.setOnClickListener(this);
        mDataBinding.llLocation.setOnClickListener(this);
        mDataBinding.ivOpenElevation.setOnClickListener(this);
        mDataBinding.llElevation.setOnClickListener(this);
        mDataBinding.ivOpenAzimuth.setOnClickListener(this);
        mDataBinding.llAzimuth.setOnClickListener(this);
        mDataBinding.ivOpenSpeed.setOnClickListener(this);
        mDataBinding.llSpeed.setOnClickListener(this);
        mDataBinding.ivOpenLongitudeAndLatitude.setOnClickListener(this);
        mDataBinding.llLongitudeAndLatitude.setOnClickListener(this);
        mDataBinding.ivOpenDecibel.setOnClickListener(this);
        mDataBinding.llDecibel.setOnClickListener(this);
        mDataBinding.ivOpenPhotographer.setOnClickListener(this);
        mDataBinding.llPhotographer.setOnClickListener(this);
        mDataBinding.tvSave.setOnClickListener(this);

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //加速度感应器
        Sensor magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        //地磁感应器
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, magneticSensor, SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_GAME);

        mHandler = new Handler();
        mRecorder = new MyMediaRecorder();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvAddCustomWatermark) {//添加自定义水印
            startActivity(CustomWatermarkActivity.class);
        } else if (id == R.id.ivOpenWatermarkVerification) {//开启水印验证
            customBean.setOpenWaterVerification(!customBean.isOpenWaterVerification());
            setData();
        } else if (id == R.id.ivOpenLogo) {//开启logo
            if (customBean.getLogoPath() == null) {
                SelPictureActivity.type = 0;
                startActivity(SelPictureActivity.class);
            } else {
                customBean.setOpenLogo(!customBean.isOpenLogo());
                setData();
            }
        } else if (id == R.id.llLogo) {//logo
            SelPictureActivity.type = 0;
            startActivity(SelPictureActivity.class);
        } else if (id == R.id.ivOpenPersonalCard) {//开启个人名片
            if (customBean.getPhotographerBean() == null) {
                startActivity(PersonalCardActivity.class);
            } else {
                customBean.setOpenPersonalCard(!customBean.isOpenPersonalCard());
                setData();
            }
        } else if (id == R.id.llPersonalCard) {//个人名片
            startActivity(PersonalCardActivity.class);
        } else if (id == R.id.ivOpenCustomText) {//开启自定义文字
            if (customBean.getText() == null) {
                showCustomTextDialog();
            } else {
                customBean.setOpenCustomText(!customBean.isOpenCustomText());
                setData();
            }
        } else if (id == R.id.llPersonalCard) {//自定义文字
            showCustomTextDialog();
        } else if (id == R.id.ivOpenNumber) {//开启编号
            customBean.setOpenNumber(!customBean.isOpenNumber());
            setData();
        } else if (id == R.id.llNumber) {//编号
            showNumberDialog();
        } else if (id == R.id.ivOpenCount) {//开启计数
            customBean.setOpenCount(!customBean.isOpenCount());
            setData();
        } else if (id == R.id.llCount) {//计数
            startActivity(CountActivity.class);
        } else if (id == R.id.ivOpenTime) {//开启时间
            customBean.setOpenTime(!customBean.isOpenTime());
            setData();
        } else if (id == R.id.llTime) {//时间
            showSelTimeDialog();
        } else if (id == R.id.ivOpenWeather) {//开启天气
            if (isHaveLocationPermission) {
                customBean.setOpenWeather(!customBean.isOpenWeather());
                setData();
            } else {
                getLocationPermission();
            }
        } else if (id == R.id.llWeather) {//天气
            if (!isHaveLocationPermission) {
                getLocationPermission();
            }
        } else if (id == R.id.ivOpenLocation) {//开启地点
            if (isHaveLocationPermission) {
                customBean.setOpenLocation(!customBean.isOpenLocation());
                setData();
            } else {
                getLocationPermission();
            }
        } else if (id == R.id.llLocation) {//地点
            if (!isHaveLocationPermission) {
                getLocationPermission();
            }
        } else if (id == R.id.ivOpenElevation) {//开启海拔
            if (isHaveLocationPermission) {
                customBean.setOpenElevation(!customBean.isOpenElevation());
                setData();
            } else {
                getLocationPermission();
            }
        } else if (id == R.id.llElevation) {//海拔
            if (!isHaveLocationPermission) {
                getLocationPermission();
            }
        } else if (id == R.id.ivOpenAzimuth) {//开启方位角
            customBean.setOpenAzimuth(!customBean.isOpenAzimuth());
            setData();
        } else if (id == R.id.ivOpenSpeed) {//开启速度
            if (isHaveLocationPermission) {
                customBean.setOpenSpeed(!customBean.isOpenSpeed());
                setData();
            } else {
                getLocationPermission();
            }
        } else if (id == R.id.llSpeed) {//速度
            if (!isHaveLocationPermission) {
                getLocationPermission();
            }
        } else if (id == R.id.ivOpenLongitudeAndLatitude) {//开启经纬度
            if (isHaveLocationPermission) {
                customBean.setOpenLongitudeAndLatitude(!customBean.isOpenLongitudeAndLatitude());
                setData();
            } else {
                getLocationPermission();
            }
        } else if (id == R.id.llLongitudeAndLatitude) {//经纬度
            if (!isHaveLocationPermission) {
                getLocationPermission();
            }
        } else if (id == R.id.ivOpenDecibel) {//开启分贝
            if (isHaveRecordAudioPermission) {
                customBean.setOpenDecibel(!customBean.isOpenDecibel());
                setData();
            } else {
                getRecordAudioPermission();
            }
        } else if (id == R.id.llDecibel) {//分贝
            if (!isHaveRecordAudioPermission) {
                getRecordAudioPermission();
            }
        } else if (id == R.id.ivOpenPhotographer) {//开启拍摄人
            if (customBean.getPhotographerBean() == null) {
                startActivity(PhotographerActivity.class);
            } else {
                customBean.setOpenPhotographer(!customBean.isOpenPhotographer());
                setData();
            }
        } else if (id == R.id.llPhotographer) {//拍摄人
            startActivity(PhotographerActivity.class);
        } else if (id == R.id.tvSave) {//保存
            List<WatermarkBean> listSp = AppSpUtils.getWatermarkList();
            listSp.get(0).setCustomBean(customBean);
            AppSpUtils.saveWatermarkList(listSp);
            ToastUtils.showShort(getString(R.string.save_suc));
            finish();
        }
    }

    @Override
    protected void initData() {
        watermarkBean = AppSpUtils.getWatermarkList().get(0);


        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            isHaveLocationPermission = false;
            mDataBinding.tvWeather.setText(getString(R.string.not_award_permission));
            mDataBinding.tvLocation.setText(getString(R.string.not_award_permission));
            mDataBinding.tvElevation.setText(getString(R.string.not_award_permission));
            mDataBinding.tvSpeed.setText(getString(R.string.not_award_permission));
            mDataBinding.tvLongitudeAndLatitude.setText(getString(R.string.not_award_permission));
            mDataBinding.customWatermark.tvWeather.setText(getString(R.string.weather) + "：" + getString(R.string.not_award_permission));
            mDataBinding.customWatermark.tvLocation.setText(getString(R.string.location) + "：" + getString(R.string.not_award_permission));
            mDataBinding.customWatermark.tvElevation.setText(getString(R.string.elevation) + "：" + getString(R.string.not_award_permission));
            mDataBinding.customWatermark.tvSpeed.setText(getString(R.string.speed) + "：" + getString(R.string.not_award_permission));
            mDataBinding.customWatermark.tvLongitudeAndLatitude.setText(getString(R.string.longitude_and_latitude) + "：" + getString(R.string.not_award_permission));
        } else {
            isHaveLocationPermission = true;
//           获取定位
            initLocation();
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            isHaveRecordAudioPermission = false;
            mDataBinding.tvDecibel.setText(getString(R.string.not_award_permission));
        } else {
            isHaveRecordAudioPermission = true;
            startTest();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        setData();
    }

    private void setData() {
        customBean = watermarkBean.getCustomBean();

        if (customBean.isOpenWaterVerification()) {
            mDataBinding.ivOpenWatermarkVerification.setImageResource(R.drawable.akai);
            mDataBinding.customWatermark.tvWatermarkVerification.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.ivOpenWatermarkVerification.setImageResource(R.drawable.aguan);
            mDataBinding.customWatermark.tvWatermarkVerification.setVisibility(View.GONE);
        }

        if (customBean.isOpenLogo()) {
            mDataBinding.ivOpenLogo.setImageResource(R.drawable.akai);
            Glide.with(mContext).load(customBean.getLogoPath()).into(mDataBinding.customWatermark.ivLogo);
            mDataBinding.customWatermark.ivLogo.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.ivOpenLogo.setImageResource(R.drawable.aguan);
            mDataBinding.customWatermark.ivLogo.setVisibility(View.GONE);
        }

        if (customBean.isOpenPersonalCard()) {
            mDataBinding.ivOpenPersonalCard.setImageResource(R.drawable.akai);
            mDataBinding.customWatermark.llCard.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.ivOpenPersonalCard.setImageResource(R.drawable.aguan);
            mDataBinding.customWatermark.llCard.setVisibility(View.GONE);
        }

        if (customBean.isOpenCustomText()) {
            mDataBinding.ivOpenCustomText.setImageResource(R.drawable.akai);
            mDataBinding.tvCustomText.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvCustomText.setVisibility(View.VISIBLE);
            mDataBinding.customWatermark.tvCustomText.setText(customBean.getText());
        } else {
            mDataBinding.ivOpenCustomText.setImageResource(R.drawable.aguan);
            mDataBinding.tvCustomText.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvCustomText.setVisibility(View.GONE);
        }

        if (customBean.isOpenNumber()) {
            mDataBinding.ivOpenNumber.setImageResource(R.drawable.akai);
            mDataBinding.tvNumber.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvNumber.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.ivOpenNumber.setImageResource(R.drawable.aguan);
            mDataBinding.tvNumber.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvNumber.setVisibility(View.GONE);
        }

        if (customBean.isOpenCount()) {
            mDataBinding.ivOpenCount.setImageResource(R.drawable.akai);
            mDataBinding.tvCount.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvCount.setVisibility(View.VISIBLE);
            mDataBinding.customWatermark.tvCount.setText(getString(R.string.count) + "：" + SPUtil.getLong(mContext, Content.count, 1L));
        } else {
            mDataBinding.ivOpenCount.setImageResource(R.drawable.aguan);
            mDataBinding.tvCount.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvCount.setVisibility(View.GONE);
        }

        if (customBean.isOpenTime()) {
            mDataBinding.ivOpenTime.setImageResource(R.drawable.akai);
            mDataBinding.tvTime.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvTime.setVisibility(View.VISIBLE);
            mDataBinding.customWatermark.tvTime.setText(getString(R.string.time) + "：" + AppConfig.DATE + " " + AppConfig.TIME);
        } else {
            mDataBinding.ivOpenTime.setImageResource(R.drawable.aguan);
            mDataBinding.tvTime.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvTime.setVisibility(View.GONE);
        }

        if (customBean.isOpenWeather()) {
            mDataBinding.ivOpenWeather.setImageResource(R.drawable.akai);
            mDataBinding.tvWeather.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvWeather.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.ivOpenWeather.setImageResource(R.drawable.aguan);
            mDataBinding.tvWeather.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvWeather.setVisibility(View.GONE);
        }

        if (customBean.isOpenLocation()) {
            mDataBinding.ivOpenLocation.setImageResource(R.drawable.akai);
            mDataBinding.tvLocation.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvLocation.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.ivOpenLocation.setImageResource(R.drawable.aguan);
            mDataBinding.tvLocation.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvLocation.setVisibility(View.GONE);
        }

        if (customBean.isOpenElevation()) {
            mDataBinding.ivOpenElevation.setImageResource(R.drawable.akai);
            mDataBinding.tvElevation.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvElevation.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.ivOpenElevation.setImageResource(R.drawable.aguan);
            mDataBinding.tvElevation.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvElevation.setVisibility(View.GONE);
        }

        if (customBean.isOpenAzimuth()) {
            mDataBinding.ivOpenAzimuth.setImageResource(R.drawable.akai);
            mDataBinding.tvAzimuth.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvAzimuth.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.ivOpenAzimuth.setImageResource(R.drawable.aguan);
            mDataBinding.tvAzimuth.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvAzimuth.setVisibility(View.GONE);
        }

        if (customBean.isOpenSpeed()) {
            mDataBinding.ivOpenSpeed.setImageResource(R.drawable.akai);
            mDataBinding.tvSpeed.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvSpeed.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.ivOpenSpeed.setImageResource(R.drawable.aguan);
            mDataBinding.tvSpeed.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvSpeed.setVisibility(View.GONE);
        }

        if (customBean.isOpenLongitudeAndLatitude()) {
            mDataBinding.ivOpenLongitudeAndLatitude.setImageResource(R.drawable.akai);
            mDataBinding.tvLongitudeAndLatitude.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvLongitudeAndLatitude.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.ivOpenLongitudeAndLatitude.setImageResource(R.drawable.aguan);
            mDataBinding.tvLongitudeAndLatitude.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvLongitudeAndLatitude.setVisibility(View.GONE);
        }

        if (customBean.isOpenDecibel()) {
            mDataBinding.ivOpenDecibel.setImageResource(R.drawable.akai);
            mDataBinding.tvDecibel.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvDecibel.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.ivOpenDecibel.setImageResource(R.drawable.aguan);
            mDataBinding.tvDecibel.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvDecibel.setVisibility(View.GONE);
        }

        if (customBean.isOpenPhotographer()) {
            mDataBinding.ivOpenPhotographer.setImageResource(R.drawable.akai);
            mDataBinding.tvPhotographer.setTextColor(Color.parseColor("#333333"));
            mDataBinding.customWatermark.tvPhotographer.setVisibility(View.VISIBLE);
            WatermarkBean.PhotographerBean photographerBean = customBean.getPhotographerBean();
            mDataBinding.customWatermark.tvPhotographer.setText(photographerBean.getTitle() + "：" + photographerBean.getContent());
        } else {
            mDataBinding.ivOpenPhotographer.setImageResource(R.drawable.aguan);
            mDataBinding.tvPhotographer.setTextColor(Color.parseColor("#999999"));
            mDataBinding.customWatermark.tvPhotographer.setVisibility(View.GONE);
        }

        List<String> listContent = customBean.getCustomTextList();
        if (listContent != null) {
            mDataBinding.customWatermark.tvCustomContent.setVisibility(View.VISIBLE);
            String content = "";
            for (int i = 0; i < listContent.size(); i++) {
                content += listContent.get(i);
                if (i != listContent.size() - 1) {
                    content += '\n';
                }
            }
            mDataBinding.customWatermark.tvCustomContent.setText(content);
        } else {
            mDataBinding.customWatermark.tvCustomContent.setVisibility(View.GONE);
        }

        if (watermarkBean.getCustomBean().getLogoPath() != null) {
            Glide.with(mContext).load(watermarkBean.getCustomBean().getLogoPath()).into(mDataBinding.ivLogoImg);
        }

        PersonalCardBean personalCardBean = AppSpUtils.getPersonalCard();
        if (personalCardBean != null) {
            Glide.with(mContext).load(personalCardBean.getImgPath()).into(mDataBinding.ivPersonalCardImg);
            Glide.with(mContext).load(personalCardBean.getImgPath()).into(mDataBinding.customWatermark.ivCardImg);
            mDataBinding.customWatermark.tvCardName.setText(personalCardBean.getName());
            mDataBinding.customWatermark.tvCardPhone.setText(personalCardBean.getPhoneNumber());
        }

        if (customBean.getText() != null) {
            mDataBinding.tvCustomText.setText(customBean.getText());
        } else {
            mDataBinding.tvCustomText.setText(getString(R.string.click_edit));
        }

        String number = customBean.getNumber();
        if (TextUtils.isEmpty(number)) {
            long mills = TimeUtils.getNowMills() / 1000;
            String millsStr = String.valueOf(mills);
            if (millsStr.length() == 10) {
                String part1 = millsStr.substring(0, 3);   // 前3位
                String part2 = millsStr.substring(3, 6);   // 中间3位
                String part3 = millsStr.substring(6, 10);  // 后4位
                String formattedNumber = part1 + "-" + part2 + "-" + part3;
                mDataBinding.tvNumber.setText(formattedNumber);
                mDataBinding.customWatermark.tvNumber.setText(getString(R.string.number) + "：" + formattedNumber);
            }
        } else {
            mDataBinding.tvNumber.setText(number);
            mDataBinding.customWatermark.tvNumber.setText(getString(R.string.number) + "：" + number);
        }

        mDataBinding.tvCount.setText(getString(R.string.count) + "：" + SPUtil.getLong(mContext, Content.count, 1L));
        mDataBinding.tvTime.setText(AppConfig.DATE + " " + AppConfig.TIME);

        if (customBean.getPhotographerBean() != null) {
            mDataBinding.tvPhotographer.setText(customBean.getPhotographerBean().getContent());
        } else {
            mDataBinding.tvPhotographer.setText(getString(R.string.click_edit));
        }
    }

    private void showCustomTextDialog() {
        CustomTextDialog dialog = new CustomTextDialog(mContext);
        dialog.setText(customBean.getText() == null ? "" : customBean.getText());
        dialog.setListener(new CustomTextDialog.Ilistener() {
            @Override
            public void clickConfirm(String text) {
                customBean.setText(text);
                customBean.setOpenCustomText(true);
                setData();
            }
        });
        dialog.show();
    }

    private void showNumberDialog() {
        NumberDialog dialog = new NumberDialog(mContext);
        dialog.setText(mDataBinding.tvNumber.getText().toString());
        dialog.setListener(new NumberDialog.Ilistener() {
            @Override
            public void clickConfirm(String text) {
                customBean.setNumber(text);
                customBean.setOpenNumber(true);
                setData();
            }
        });
        dialog.show();
    }

    private void showSelTimeDialog() {
        SelTimeDialog dialog = new SelTimeDialog(mContext);
        dialog.setListener(new SelTimeDialog.Ilistener() {
            @Override
            public void clickConfirm(long date) {
                AppConfig.DATE = TimeUtils.millis2String(date, new SimpleDateFormat("yyyy-MM-dd"));
                AppConfig.TIME = TimeUtils.millis2String(date, new SimpleDateFormat("HH:mm"));
                customBean.setOpenTime(true);
                setData();
            }
        });
        dialog.show();
    }

    private void getLocationPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_location_permission));
        PermissionUtils.permission(Manifest.permission.ACCESS_FINE_LOCATION).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                isHaveLocationPermission = true;
                initLocation();
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    private void getRecordAudioPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_record_audio_permission));
        PermissionUtils.permission(Manifest.permission.RECORD_AUDIO).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                isHaveRecordAudioPermission = true;
                startTest();
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    private LocationManager mLocationMgr; // 声明一个定位管理器对象


    private boolean isLocationEnable = false; // 定位服务是否可用

    public void initLocation() {
        mLocationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria(); // 创建一个定位准则对象
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 设置定位精确度
        criteria.setAltitudeRequired(true); // 设置是否需要海拔信息
        criteria.setBearingRequired(true); // 设置是否需要方位信息
        criteria.setCostAllowed(true); // 设置是否允许运营商收费
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 设置对电源的需求
        // 获取定位管理器的最佳定位提供者
        String bestProvider = mLocationMgr.getBestProvider(criteria, true);
        if (bestProvider != null && mLocationMgr.isProviderEnabled(bestProvider)) { // 定位提供者当前可用
            beginLocation(bestProvider); // 开始定位
            isLocationEnable = true;
        } else { // 定位提供者暂不可用
            ToastUtils.showShort(getString(R.string.please_open_location_service));
            isLocationEnable = false;
        }
    }

    private void beginLocation(String method) {

        // 检查当前设备是否已经开启了定位功能

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)

                != PackageManager.PERMISSION_GRANTED) {
            ToastUtils.showShort(getString(R.string.please_open_location_permission));
            return;

        }

        // 设置定位管理器的位置变更监听器

        mLocationMgr.requestLocationUpdates(method, 300, 0, mLocationListener);

        // 获取最后一次成功定位的位置信息

        Location location = mLocationMgr.getLastKnownLocation(method);
        if (location != null) {
            setLocation(location); // 显示定位结果文本
        }


    }
    // 定义一个位置变更监听器

    private LocationListener mLocationListener = new LocationListener() {

        @Override

        public void onLocationChanged(Location location) {
            if (location != null) {
                setLocation(location); // 显示定位结果文本
            }
        }

        @Override

        public void onProviderDisabled(String arg0) {
        }

        @Override

        public void onProviderEnabled(String arg0) {
        }

        @Override

        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        }

    };

    private void setLocation(Location location) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        // 创建DecimalFormat实例用于格式化数值
        DecimalFormat df = new DecimalFormat("#.##");

        // 获取并显示位置名称
        String locationStr = getLocationName(latitude, longitude);

        // 显示海拔信息
        if (location.hasAltitude()) {
            double altitude = location.getAltitude();
            String altitudeStr = df.format(altitude) + "米";
            mDataBinding.tvElevation.setText(altitudeStr);
            mDataBinding.customWatermark.tvElevation.setText(getString(R.string.elevation) + "：" + altitudeStr);
        } else {
            String altitudeStr = "0.0米";
            mDataBinding.tvElevation.setText(altitudeStr);
            mDataBinding.customWatermark.tvElevation.setText(getString(R.string.elevation) + "：" + altitudeStr);
        }

        // 显示速度信息
        if (location.hasSpeed()) {
            float speed = location.getSpeed();
            int speedInt = (int) Math.round(speed * 3.6); // 转换为km/h并四舍五入为整数
            String speedStr = speedInt + "公里/小时";
            mDataBinding.tvSpeed.setText(speedStr);
            mDataBinding.customWatermark.tvSpeed.setText(getString(R.string.speed) + "：" + speedStr);
        } else {
            String speedStr = "0公里/小时";
            mDataBinding.tvSpeed.setText(speedStr);
            mDataBinding.customWatermark.tvSpeed.setText(getString(R.string.speed) + "：" + speedStr);
        }

        // 显示经纬度信息
        String latStr = df.format(Math.abs(latitude)) + "°" + (latitude >= 0 ? "N" : "S");
        String lonStr = df.format(Math.abs(longitude)) + "°" + (longitude >= 0 ? "E" : "W");
        String latLonStr = latStr + ", " + lonStr;
        mDataBinding.tvLongitudeAndLatitude.setText(latLonStr);
        mDataBinding.customWatermark.tvLongitudeAndLatitude.setText(getString(R.string.longitude_and_latitude) + "：" + latLonStr);

        if (!TextUtils.isEmpty(locationStr)) {
            mLocationMgr.removeUpdates(mLocationListener);
        }
    }

    private String getLocationName(double lat, double lon) {
        // 创建DecimalFormat实例用于格式化经纬度
        DecimalFormat df = new DecimalFormat("#.#####");

        // 方案1：使用Android原生Geocoder
        if (Geocoder.isPresent()) {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
                if (!addresses.isEmpty()) {
                    Address address = addresses.get(0);
                    String location = address.getAddressLine(address.getMaxAddressLineIndex());
                    mDataBinding.tvLocation.setText(location);
                    mDataBinding.customWatermark.tvLocation.setText(getString(R.string.location) + "：" + location);
                    getCity24(CityUtils.getCityId(addresses.get(0).getLocality()));
                    return location;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 如果Geocoder不可用，只显示格式化的经纬度
        String latStr = df.format(Math.abs(lat)) + "°" + (lat >= 0 ? "N" : "S");
        String lonStr = df.format(Math.abs(lon)) + "°" + (lon >= 0 ? "E" : "W");
        String coordsOnly = latStr + ", " + lonStr;
        mDataBinding.tvLocation.setText(coordsOnly);
        return "";
    }

    private void getCity24(String cityId) {
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("cityId", cityId);
        /*   stringStringHashMap.put("token", "008d2ad9197090c5dddc76f583616606");*/
        OkhttpUtils.getInstance().postRequest("whapi/json/alicityweather/forecast24hours", stringStringHashMap, new OkhttpUtils.HttpCallBack() {
            @Override
            public void onSusscess(String data) {
                Hours24Bean cityInfoBean = new Gson().fromJson(data, Hours24Bean.class);
                if (cityInfoBean.getCode() == 0) {
                    List<Hours24Bean.DataBean.HourlyBean> hourList = cityInfoBean.getData().getHourly();
                    if (!hourList.isEmpty()) {
                        //当前气温
                        int temp = (int) hourList.get(0).getTemp();
                        mDataBinding.tvWeather.setText(hourList.get(0).getCondition() + " " + temp + "℃");
                        mDataBinding.customWatermark.tvWeather.setText(getString(R.string.weather) + "：" + hourList.get(0).getCondition() + " " + temp + "℃");
                    }
                }

            }

            @Override
            public void onFail(String meg) {
                Log.e("sssssss", meg);
            }
        });
    }

    float[] accelerometerValues = new float[3];

    float[] magneticValues = new float[3];

    @Override
    public void onSensorChanged(SensorEvent event) {
        // 判断当前是加速度感应器还是地磁感应器
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            //赋值调用clone方法
            accelerometerValues = event.values.clone();
        } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            //赋值调用clone方法
            magneticValues = event.values.clone();
        }
        if (accelerometerValues != null && magneticValues != null) {
            long curTime = System.currentTimeMillis();
            if (curTime - lastUpdateTime < 500) return;
            lastUpdateTime = curTime;
            calculateOrientation(); // 加速度和磁场强度两个都有了，才能计算磁极的方向
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    //计算方位
    private void calculateOrientation() {
        float[] R = new float[9];
        float[] values = new float[3];
        SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticValues);
        sensorManager.getOrientation(R, values);
        //values[0]的取值范围是-180到180度。
        double value = Math.toDegrees(values[0]);
        //+-180表示正南方向，0度表示正北，-90表示正西，+90表示正东

        // 将value转换为0-360度范围
        if (value < 0) {
            value = value + 360;
        }

        String direction = "";
        if ((value >= 337.5 && value <= 360) || (value >= 0 && value < 22.5)) {
            direction = "北";
        } else if (value >= 22.5 && value < 67.5) {
            direction = "东北";
        } else if (value >= 67.5 && value < 112.5) {
            direction = "东";
        } else if (value >= 112.5 && value < 157.5) {
            direction = "东南";
        } else if (value >= 157.5 && value < 202.5) {
            direction = "南";
        } else if (value >= 202.5 && value < 247.5) {
            direction = "西南";
        } else if (value >= 247.5 && value < 292.5) {
            direction = "西";
        } else if (value >= 292.5 && value < 337.5) {
            direction = "西北";
        }

        // 更新UI显示方位角
        DecimalFormat df = new DecimalFormat("0");
        String azimuthText = getString(com.lzb.watermarkcamera.R.string.azimuth) + "：" + direction + " " + df.format(value) + "° ";
        mDataBinding.customWatermark.tvAzimuth.setText(azimuthText);
        mDataBinding.tvAzimuth.setText(direction + " " + df.format(value) + "° ");
    }

    //开始检测
    private void startTest() {
        String musicPath = FileUtil.generateFilePath(Content.Temp, ".mp3");
        try {
            mRecorder.setMyRecAudioFile(FileUtils.getFileByPath(musicPath));
            if (mRecorder.startRecorder()) {
                hasRecord = true;
                startTime();
            } else {
                ToastUtils.showShort(R.string.audio_fail_tips);
            }
        } catch (Exception e) {
            ToastUtils.showShort(R.string.audio_fail_tips2);
            e.printStackTrace();
        }
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTime();
        FileUtils.deleteFilesInDir(PathUtils.getFilesPathExternalFirst() + Content.Temp);
    }

}